<template>
  <div>
    <a-card>
      <a-form name="project_search" :model="formState" autocomplete="off" @finish="onFinish">
        <a-row>
          <a-col :span="8">
            <a-form-item label="项目名称" name="projectname" class="projectItem">
              <a-input
                v-model:value="formState.projectname"
                allowClear
                placeholder="请输入项目名称"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="人员" name="wwusername" class="projectItem">
              <dept-user-select
                ref="deptUserSelect"
                @change="handlUserIdsChange"
              ></dept-user-select>
            </a-form-item>
          </a-col>
          <!--          <a-col :span="10"></a-col>-->
          <a-col :span="8" style="text-align: right">
            <a-space justify="end">
              <a-form-item>
                <a-button @click="reflsh"> 重置 </a-button>
              </a-form-item>
              <a-form-item>
                <a-button type="primary" html-type="submit"> 查询 </a-button>
              </a-form-item>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
      <a-row>
        <a-col :span="4">
          <a-form-item>
            <a-button type="primary" @click="handleProjectAdd"> 新增项目 </a-button>
          </a-form-item>
        </a-col>
        <a-col :span="20"></a-col>
      </a-row>
      <a-table
        v-if="dataSource"
        :scroll="{ y: 540 }"
        :columns="ucolumns"
        :data-source="dataSource"
        :pagination="upagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record, index, text }">
          <template v-if="column.key == 'index'">
            {{ (upagination.current - 1) * upagination.pageSize + parseInt(index) + 1 }}
          </template>
          <template v-else-if="column.key == 'projectname'">
            <div class="editable-cell">
              <div
                v-if="editableData['projectname:' + record.id]"
                class="editable-cell-input-wrapper"
              >
                <a-input
                  v-model:value="editableData['projectname:' + record.id].projectname"
                  @pressEnter="saveProjectname(record.id)"
                ></a-input>
                <check-outlined
                  class="editable-cell-icon-check"
                  @click="saveProjectname(record.id)"
                ></check-outlined>
              </div>
              <div v-else class="editable-cell-text-wrapper beyond_hiding">
                <a-tooltip>
                  <template #title>
                    {{ text || ' ' }}
                  </template>
                  {{ text || ' ' }}
                </a-tooltip>
                <edit-outlined
                  class="editable-cell-icon"
                  @click="edit('projectname:' + record.id)"
                />
              </div>
            </div>
          </template>
          <template v-else-if="column.key == 'clientcompany'">
            <div class="editable-cell">
              <div
                v-if="editableData['clientcompany:' + record.id]"
                class="editable-cell-input-wrapper"
              >
                <a-input
                  v-model:value="editableData['clientcompany:' + record.id].clientcompany"
                  @pressEnter="saveClientcompany(record.id)"
                ></a-input>
                <check-outlined
                  class="editable-cell-icon-check"
                  @click="saveClientcompany(record.id)"
                ></check-outlined>
              </div>
              <div v-else class="editable-cell-text-wrapper beyond_hiding">
                <a-tooltip>
                  <template #title>
                    {{ text || ' ' }}
                  </template>
                  {{ text || ' ' }}
                </a-tooltip>
                <edit-outlined
                  class="editable-cell-icon"
                  @click="edit('clientcompany:' + record.id)"
                />
              </div>
            </div>
          </template>
          <template v-else-if="column.key === 'finished'">
            <div class="beyond_hiding">
              <a-tag v-if="record.finished == '3201'" color="processing"> 进行中 </a-tag>
              <a-tag v-else color="success"> 已完成 </a-tag>
            </div>
          </template>
          <template v-else-if="column.key === 'puserList'">
            <div v-if="record.puserList" class="beyond_hiding">
              <div v-if="record.puserList.mgar">
                <a-tooltip placement="topLeft" class="tooltip-custom" color="white">
                  <template #title>
                    <div v-if="record.puserList">
                      <span style="color: black">管理者：</span>
                      <a-tag
                        v-for="(mgar, index) in record.puserList.mgar"
                        :key="index"
                        color="success"
                      >
                        <UserOutlined />
                        {{ mgar.wwusername }}
                      </a-tag>
                      <br />
                      <span style="color: black">参与人员：</span>
                      <a-tag v-for="(user, index) in record.puserList.user" :key="index">
                        <UserOutlined />
                        {{ user.wwusername }}
                      </a-tag>
                    </div>
                  </template>
                  <div v-if="record.puserList.mgar">
                    <a-tag
                      v-for="(mgar, index) in record.puserList.mgar"
                      :key="index"
                      color="success"
                    >
                      <user-outlined />
                      {{ mgar.wwusername }}
                    </a-tag>
                    <a-tag v-for="(user, index) in record.puserList.user" :key="index">
                      <user-outlined />
                      {{ user.wwusername }}
                    </a-tag>
                  </div>
                </a-tooltip>
              </div>
            </div>
          </template>
          <template v-else-if="column.key === 'action'">
            <a href="#" style="color: #2196f8" @click="handleProjectUser(record)">编辑</a>
            <a-divider type="vertical" />
            <a-dropdown>
              <a style="color: #2196f8">操作<DownOutlined /></a>
              <template #overlay>
                <a-menu>
                  <a-menu-item>
                    <!-- 完成 -->
                    <a-popconfirm
                      title="确认完成"
                      @confirm="updateProjectFinished('projectname:' + record.id)"
                    >
                      <template #icon>
                        <question-circle-outlined style="color: red" />
                      </template>
                      <a href="#" style="color: #2196f8" v-if="record.finished == '3201'">完成</a>
                    </a-popconfirm>
                  </a-menu-item>
                  <a-menu-item>
                    <a-popconfirm
                      title="确定删除吗？"
                      ok-text="确定"
                      cancel-text="取消"
                      @confirm="deleteProject('projectname:' + record.id)"
                    >
                      <a href="#" style="color: #2196f8">删除</a>
                    </a-popconfirm>
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </template>
      </a-table>
      <project-edit v-if="showEdit" ref="projectEdit" :label-edit="labelEdit"></project-edit>
      <!-- 编辑弹窗 -->
      <a-modal v-model:visible="openEditProjectUser" title="人员编辑" @ok="handleProjectUserOk">
        <a-form>
          <a-form-item label="项目名称" class="projectItem">
            <span>{{ projectUser.projectname }}</span>
          </a-form-item>
          <a-form-item label="参与项目人员" class="projectItem">
            <tree-list
              :checked-keys="projectUser.wwuserids"
              @getkvList="getSonValue"
              @getmyKVList="changeMymagerOptions"
            ></tree-list>
          </a-form-item>
          <a-form-item label="管理者" class="projectItem">
            <a-select
              v-model:value="projectUser.mgruserids"
              :options="magerOptions"
              mode="multiple"
              :show-search="true"
              optionFilterProp="value"
              allowClear
              :field-names="{ label: 'value', value: 'key' }"
              placeholder="请选择管理者"
              style="width: 200px"
            ></a-select>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, toRaw, reactive } from 'vue';
import { message } from 'ant-design-vue/es';
import { cloneDeep } from 'lodash-es';
import { UserOutlined, CheckOutlined, EditOutlined } from '@ant-design/icons-vue';
import type { UnwrapRef } from 'vue';
import { getProjectPage, save, deleteProjectById, editUser } from '@/api/base/project/project';
import { APP_USER } from '@/enums/cacheEnum';
import { Storage } from '@/utils/Storage';
import ProjectEdit from '@/views/base/project/projectEdit.vue';
import DeptUserSelect from '@/views/base/project/deptUserSelect.vue';
import treeList from '@/components/basic/treeList.vue';

const dataSource = ref([]);
const tenantid = ref(Storage.Get(APP_USER).tenantid);
const ucolumns = [
  {
    title: '序号',
    width: 60,
    key: 'index',
    align: 'center',
    fixed: 'left',
  },
  {
    title: '名称',
    dataIndex: 'projectname',
    key: 'projectname',
    align: 'left',
    width: '15%',
    onFilter: (value: string, record: any) => record.projectname.indexOf(value) === 0,
    sorter: (a: any, b: any) => a.projectname.localeCompare(b.projectname), // 使用 localeCompare 进行字典顺序比较
    sortDirections: ['ascend', 'descend'], // 支持升序和降序
  },
  {
    title: '对方单位',
    dataIndex: 'clientcompany',
    key: 'clientcompany',
    align: 'left',
    width: '15%',
    onFilter: (value: string, record: any) => record.clientcompany.indexOf(value) === 0,
    sorter: (a: any, b: any) => a.clientcompany.localeCompare(b.clientcompany), // 使用 localeCompare 进行字典顺序比较
    sortDirections: ['ascend', 'descend'], // 支持升序和降序
  },
  {
    title: '项目参与人员',
    dataIndex: 'puserList',
    key: 'puserList',
    align: 'left',
  },

  {
    title: '状态',
    dataIndex: 'finished',
    key: 'finished',
    align: 'center',
    width: '10%',
  },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
    width: 180,
    fixed: 'right',
    align: 'center',
    scopedSlots: { customRender: 'operation' },
  },
];
const upagination = ref({
  // 表格分页参数
  defaultPageSize: 20,
  total: 0,
  current: 1,
  pageSize: 20,
  showTotal: (total) => `共${total}条数据`,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
});
const queryParam = ref({
  f_tenantid: tenantid.value,
  pageNumber: null,
  pageSize: 10,
});
const formState = reactive({
  projectname: '',
  wwuserids: [],
  wwusername: '',
});
const showEdit = ref(false);
const labelEdit = ref('');
const projectEdit: any = ref(null);
const deptUserSelect: any = ref(null);
const openUpdateVersion = ref(false);
const projectVerSion = ref({
  projectcode: '',
  projectname: '',
  tenantid: '',
  clientcompany: '',
});
const projectUser = ref({
  projectid: -1,
  projectname: '',
  tenantid: tenantid.value,
  wwuserids: [],
  mgruserids: [],
});
//管理人选项
const magerOptions = ref([]);
//获取表单数据
const getDataSource = async () => {
  const { code, data } = await getProjectPage(queryParam.value);
  if (code == 0) {
    dataSource.value = data.records;
    upagination.value.total = data.total;
    upagination.value.current = data.current;
    upagination.value.pageSize = data.size;
  } else {
    message.error('查询失败');
  }
};
const editableData: UnwrapRef<Record<string, any>> = reactive({});
const openEditProjectUser = ref<boolean>(false); //修改的弹窗
//项目名称修改按钮
const edit = (key: string) => {
  let redkey = key.split(':')[1];
  editableData[key] = cloneDeep(dataSource.value.filter((item) => redkey == item.id.toString())[0]);
};
//翻页、设置页数量时触发，将分页组建的当前页与大小传给后台
const handleTableChange = (pagination) => {
  queryParam.value.pageNumber = pagination.current;
  queryParam.value.pageSize = pagination.pageSize;
  getDataSource(); // 重新获取数据
};
//项目名称保存
const saveProjectname = async (id: number) => {
  const oldData = dataSource.value.filter((item) => id === item.id)[0];
  if (oldData.projectname == editableData['projectname:' + id].projectname) {
    message.info('未进行修改');
  } else {
    const saveProject = {
      id: editableData['projectname:' + id].id,
      projectname: editableData['projectname:' + id].projectname,
      tenantid: tenantid.value,
    };
    await save(saveProject).then((res) => {
      if (res.code == 0) {
        message.success('修改项目名称成功');
      } else {
        message.error('项目名称修改失败');
      }
    });
    dataSource.value.filter((item) => id === item.id)[0].projectname =
      editableData['projectname:' + id].projectname;
  }
  delete editableData['projectname:' + id];
};
//对方单位保存
const saveClientcompany = async (id: number) => {
  const oldData = dataSource.value.filter((item) => id === item.id)[0];
  if (oldData.clientcompany == editableData['clientcompany:' + id].clientcompany) {
    message.info('未进行修改');
  } else {
    const saveProject = {
      id: editableData['clientcompany:' + id].id,
      clientcompany: editableData['clientcompany:' + id].clientcompany,
      tenantid: tenantid.value,
    };
    await save(saveProject).then((res) => {
      if (res.code == 0) {
        message.success('对方单位修改成功');
      } else {
        message.error('对方单位修改失败');
      }
    });
    dataSource.value.filter((item) => id === item.id)[0].clientcompany =
      editableData['clientcompany:' + id].clientcompany;
  }
  delete editableData['clientcompany:' + id];
};
//项目搜索按钮触发
const onFinish = async (values: any) => {
  const queryNumber = {
    pageSize: upagination.value.pageSize,
    f_tenantid: tenantid.value,
  };
  if (values.projectname && values.projectname.length > 0) {
    queryNumber['f_projectname'] = values.projectname;
  }
  if (formState.wwuserids && formState.wwuserids.length > 0) {
    queryNumber['wwuserids'] = toRaw(formState.wwuserids);
  }
  if (values.wwusername && values.wwusername.length > 0) {
    queryNumber['wwusername'] = values.wwusername;
  }
  console.log('查询参数', queryNumber);
  const { code, data } = await getProjectPage(queryNumber);
  if (code == 0) {
    dataSource.value = data.records;
    upagination.value.total = data.total;
    upagination.value.current = data.current;
    upagination.value.pageSize = data.size;
  } else {
    message.error('查询失败');
  }
};
//人员修改
const handleProjectAdd = () => {
  showEdit.value = true;
  labelEdit.value = '项目添加';
  projectEdit.value.handelEdit();
};
//删除项目
const deleteProject = (id) => {
  deleteProjectById(id).then((res) => {
    if (res.code == 0) {
      message.success('删除项目成功');
      reflsh();
    } else {
      message.error('删除项目失败');
    }
  });
};
//重置表单
const reflsh = async () => {
  const param = {
    f_tenantid: tenantid.value,
    pageSize: upagination.value.pageSize,
  };
  const { code, data } = await getProjectPage(param);
  if (code == 0) {
    dataSource.value = data.records;
    upagination.value.total = data.total;
    upagination.value.current = data.current;
    upagination.value.pageSize = data.size;
    formState.projectname = '';
    formState.wwuserids = [];
    deptUserSelect.value.allClear();
  } else {
    message.error('查询失败');
  }
};

// 完成项目的方法
const updateProjectFinished = async (id) => {
  const projectFinished = {
    id: id,
    finished: 3200,
    tenantid: tenantid.value,
  };
  await save(projectFinished).then((res) => {
    if (res.code == 0) {
      message.success('操作成功');
    } else {
      message.error('项目操作失败');
    }
  });
};
//处理输入框人员变化事件
const handlUserIdsChange = (value) => {
  const wwuerids = toRaw(value);
  formState.wwuserids = wwuerids;
};
// 处理点击编辑
const handleProjectUser = (record) => {
  console.log(projectUser.value, 'wfhoiwjf9ojfow9');
  projectUser.value.projectid = record.id;
  projectUser.value.projectname = record.projectname;
  projectUser.value.tenantid = tenantid.value;
  let mgarids = [];
  let userids = [];
  if (record.puserList) {
    if (record.puserList.mgar && record.puserList.mgar.length > 0) {
      mgarids = record.puserList.mgar.map((item) => item.wwuserid);
    }
    if (record.puserList.user && record.puserList.user.length > 0) {
      userids = record.puserList.user.map((item) => item.wwuserid);
    }
  }
  projectUser.value.mgruserids = mgarids;
  projectUser.value.wwuserids = userids.concat(mgarids);
  openEditProjectUser.value = true;
};
// 接收子组件传过来的值
const getSonValue = (list) => {
  projectUser.value.wwuserids = list.map((item) => item.key);
  magerOptions.value = list;
  // console.log('editParam', list)
};
//处理人员编辑
const handleProjectUserOk = async () => {
  const res = await editUser({
    projectId: projectUser.value.projectid,
    mgruserids: projectUser.value.mgruserids,
    userIds: projectUser.value.wwuserids,
    tenantid: projectUser.value.tenantid,
  });
  if (res.code == 0) {
    message.success('编辑成功');
    openEditProjectUser.value = false;
    reflsh();
  }
};
// 改变管理员选项changeMymagerOptions
const changeMymagerOptions = (value) => {
  magerOptions.value = value;
  const temp = value.map((item) => item.key);
  const tempSet = new Set(temp);
  projectUser.value.mgruserids = projectUser.value.mgruserids.filter((id) => tempSet.has(id));
};

// 页面初始化
onMounted(() => {
  getDataSource();
  openUpdateVersion.value = false;
});

defineOptions({
  name: 'ProjectList',
});
</script>
<style lang="less" scoped>
//列修改样式
.editable-cell {
  position: relative;

  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    margin-top: 4px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}

.beyond_hiding {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

// form表单样式
.projectItem {
  padding-left: 0px;
  padding-right: 20px;

  ::v-deep .ant-col {
    width: auto;
    height: auto;
  }
}

//按钮
.btn_primary_color:hover,
.btn_primary_color:focus {
  background-color: #0072c6;
  opacity: 0.8;
  color: #fff;
  border: 2px solid #0072c6;
}
</style>
